package com.interview.domain;

import com.interview.strategy.DiscountPricingStrategy;
import com.interview.strategy.NormalPricingStrategy;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;


public class Supermarket {
    Map<String,Fruit> products = new HashMap<>();
    List<Promotion> promotionList = new ArrayList<>();

    public void addProducts(List<Fruit> goods){
        for (Fruit fruit : goods) {
            products.put(fruit.getName(),fruit);
        }
    }

    public void addPromotion(Promotion promotion){
        promotionList.add(promotion);
        System.out.println("优惠券【"+promotion.getDesc()+"】添加成功");
    }

    public Order calculateTotalCost(Cart cart) {
        Order order = new Order();
        Map<String, Integer> cartVal = cart.getCart();
        for (String fruitName : cartVal.keySet()) {
            Fruit fruit = products.get(fruitName);
            assert fruit != null:"未找到该产品";
            Integer quantity = cartVal.get(fruitName);
            OrderItem orderItem = fruit.calculateCost(quantity);
            order.addOrderItem(orderItem);
        }
        Promotion promotion = applyPromotions(order.getOriginalTotal());
        if(promotion!=null){
            order.setCouponVal(promotion.getMaxDiscountAmount());
        }
        return order;
    }
    private Promotion applyPromotions(BigDecimal totalCost) {
        if(promotionList.isEmpty()) {
            return null;
        }
        LocalDateTime now = LocalDateTime.now();
        //筛选优惠券
        Optional<Promotion> max = promotionList.stream().filter(p -> now.isAfter(p.getStartTime())
                        && now.isBefore(p.getEndTime())
                        && p.getThresholdAmount().compareTo(totalCost) <= 0)
                .max(Comparator.comparing(Promotion::getMaxDiscountAmount));
        return max.orElse(null);
    }
    public void updateDiscount(String fruitName, double discount) {
        Fruit fruit = products.get(fruitName);
        assert fruit!=null:"该产品不存在";
        assert discount>=0&&discount<=1:"折扣不得小于0且折扣不得大于1";
        if(discount>0){
            fruit.setPricingStrategy(new DiscountPricingStrategy(discount));
        }else{
            fruit.setPricingStrategy(new NormalPricingStrategy());
        }
        products.put(fruitName,fruit);
    }
}
